import {onMounted, ref} from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import {addClusterMarker} from "../util/utils"
import {biApi} from "@/views/vms-bi/biApi";
import {useInterval} from "vue-hooks-plus";

export const useInitMapHook = (id)=>{
    let map = ref(null)
    let AMap1 = ref(null)



 


    /*
    * 初始化地图
    * */
    const initMap =async (carListData)=>{
       await AMapLoader.load({
            key: "3919f0b2f9b3f928d7e3f348d4d5e4f2", //申请好的Web端开发者 Key，调用 load 时必填
            version: "2.0", //指定要加载的 JS API 的版本，缺省时默认为 1.4.15

        }).then((AMap) => {
            map = new AMap.Map(id,{
                zoom: 6, // 设置地图的缩放级别
                viewMode: "2D",
                // center:['106.5478767','29.5647398']
            });
            map.setMapStyle("amap://styles/darkblue"); // 修改地图的显示样式为暗色主题
            AMap1 = AMap

           // 地图添加车辆标记点
           // addTextMarker(carListData,AMap,map)
           let cluster = null;
           useInterval(() => {
               // 定时任务添加聚合点
               get_real_time_monitoring().then(res=>{
                   let {points,styles,_renderMarker,_renderClusterMarker} = addClusterMarker(res,AMap,map);
                   cluster = map.plugin(["AMap.MarkerCluster"], function () {
                       cluster = new AMap.MarkerCluster(
                           map, //地图实例
                           points, //海量点数据，数据中需包含经纬度信息字段 lnglat
                           {
                               gridSize: 60, //数据聚合计算时网格的像素大小
                               renderClusterMarker: _renderClusterMarker, //自定义聚合点样式
                               renderMarker: _renderMarker, //自定义非聚合点样式

                           }
                       );
                   });
               })
           }, 1000*30,{
               immediate:true
           })







        })
            .catch((e) => {
                console.error(e); //加载错误提示
            });
    }


    // 获取车辆实时数据
    const get_real_time_monitoring = ()=>{
       return  biApi.get_real_time_monitoring().then(res=>{
           return res.map(item => {
                return {
                    lonGcj: item.longitude,
                    latGcj: item.latitude,
                    licensePlate: `${item.car_number}(${item.driver_name})`,
                    status: item.status
                }
            })
        })
    }


    onMounted(async ()=>{
       await initMap()


    })

    return {map,AMap:AMap1};
}